package pers.zh.parking.mvp.ui.activity;

import android.Manifest;
import android.animation.Animator;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.Photo;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.Query;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.bumptech.glide.Glide;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.squareup.picasso.Picasso;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;
import per.goweii.anylayer.AnimatorHelper;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.DragLayout;
import per.goweii.anylayer.Layer;
import pers.zh.parking.R;
import pers.zh.parking.amap.NaviInfoCallback;
import pers.zh.parking.common.Const;
import pers.zh.parking.data.UserSettings;
import pers.zh.parking.data.entity.ParkingLot;
import pers.zh.parking.di.component.DaggerMapComponent;
import pers.zh.parking.mvp.contract.MapContract;
import pers.zh.parking.mvp.presenter.MapPresenter;
import pers.zh.parking.mvp.ui.adapter.LotsAdapter;
import pers.zh.parking.utils.DrawableUtil;
import pers.zh.parking.utils.MyUtils;
import pers.zh.parking.utils.UIUtils;
import pers.zjc.commonlibs.util.BarUtils;
import pers.zjc.commonlibs.util.GsonUtils;
import pers.zjc.commonlibs.util.KeyboardUtils;
import pers.zjc.commonlibs.util.LogUtils;
import pers.zjc.commonlibs.util.ObjectUtils;
import pers.zjc.commonlibs.util.StringUtils;
import pers.zjc.commonlibs.util.ToastUtils;
import timber.log.Timber;

import static com.jess.arms.utils.Preconditions.checkNotNull;

public class MapActivity extends BaseActivity<MapPresenter>
        implements MapContract.View, OnPoiSearchListener, AMap.OnMapClickListener, AMap.OnMapTouchListener {

    @BindView(R.id.loadingView)
    ProgressBar loadingView;
    @BindView(R.id.mapView)
    MapView mMapView;
    @BindView(R.id.bar_search)
    RelativeLayout rlSearch;
    @BindView(R.id.etSearch)
    EditText etSearch;
    @BindView(R.id.fabLocate)
    FloatingActionButton fabLocate;
    @BindView(R.id.fabRefresh)
    FloatingActionButton fabRefresh;
    @BindView(R.id.navigationView)
    NavigationView navigationView;

    private AMap aMap;
    private double lat;
    private double lng;
    private UiSettings mUiSettings;

    private LatLng curLatLng;

    // 中心点跟随移动
    private boolean followMove = true;
    // 是否首次获取定位
    private boolean firstLocated = true;
    // 是否模拟数据
    private boolean mockData = false;

    private Drawable drClear;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMapComponent //如找不到该类,请编译一下项目
                           .builder().appComponent(appComponent).view(this).build().inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_map; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @SuppressLint("CheckResult")
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        setupView();
    }

    private void initNavigationView() {
        View headerView = navigationView.getHeaderView(0);
        TextView tvUserName = headerView.findViewById(R.id.tvUserName);
        TextView tvSign = headerView.findViewById(R.id.tvSign);
        ImageView ivAvatar = headerView.findViewById(R.id.ivAvatar);
        tvUserName.setText(getResources().getString(R.string.to_login));
        tvSign.setText(getResources().getString(R.string.signature));
        // 头像
        ivAvatar.setOnClickListener(v -> launchActivity(new Intent(this, UserActivity.class)));
        // 菜单项点击
        navigationView.setNavigationItemSelectedListener(menuItem -> {
            switch (menuItem.getItemId()) {
                case R.id.nav_notification:
                    launchActivity(new Intent(MapActivity.this, NoticeActivity.class));
                    break;
                case R.id.nav_reserve_history:
                    switchToReservationPage();
                    break;
                case R.id.nav_park_history:
                    launchActivity(new Intent(MapActivity.this, ParkActivity.class));
                    break;
                case R.id.nav_my_cars:
                    launchActivity(new Intent(MapActivity.this, MyCarsActivity.class));
                    break;
                case R.id.nav_my_eval:
                    launchActivity(new Intent(MapActivity.this, EvalActivity.class));
                    break;
                case R.id.nav_log_out:
                    UIUtils.createConfirmDialog(MapActivity.this, "是否要退出当前用户?", true,
                            (dialog, which) -> {
                                UserSettings.getInstance().setLogin(false);
                                launchActivity(new Intent(MapActivity.this, LoginActivity.class));
                            }, (dialog, which) -> {}).show();

                    break;
                default:
                    break;
            }
            return true;
        });
        UserSettings settings = UserSettings.getInstance();
        tvUserName.setText(settings.isLogin() ? settings.getUserName() : "去登录");
        tvSign.setText(settings.getDescription());
//        Picasso.with(ivAvatar.getContext())
//               .load("http://192.168.1.138:8091/parking/file/download1")
//               .into(ivAvatar);

    }

    private void switchToReservationPage() {
        Intent intent = new Intent(this, ReservationActivity.class);
        intent.putExtra(Const.Keys.KEY_CUR_LOCATION, curLatLng);
        launchActivity(intent);
    }

    @SuppressLint("CheckResult")
    private void setupView() {
        // 允许窗口扩展到屏幕之外
        getWindow().addFlags(LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        // 出现Toolbar被顶到状态栏里面去。这时候就需要给它设置一个marginTop高度等于状态栏高度就行了
        BarUtils.addMarginTopEqualStatusBarHeight(rlSearch);
        // 状态栏字体颜色
        BarUtils.setStatusBarLightMode(this, true);
        // 侧滑栏
        initNavigationView();
        // 搜索控件
        configSearchEvent();
        // 右下角悬浮按钮
        configFabEvent();
        // 请求权限
        requestPermission();
    }

    private void configFabEvent() {
        fabRefresh.setOnClickListener(view -> {
            if (aMap == null || curLatLng == null) {
                return;
            }
            aMap.animateCamera(CameraUpdateFactory.changeLatLng(curLatLng));
            mPresenter.loadLotsAround(curLatLng);
        });
        fabLocate.setOnClickListener(view -> {
            if (aMap == null || curLatLng == null) {
                return;
            }
            aMap.animateCamera(CameraUpdateFactory.changeLatLng(curLatLng));
        });
    }

    private void configSearchEvent() {
        etSearch.setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent event) {
                //以下方法防止两次发送请求
                if (i == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            String keyWord = etSearch.getText().toString();
                            if (mockData) {
                                searchLotsAround(keyWord, "");
                            }
                            else {
                                mPresenter.searchLots(lat, lng, Const.Map.DEFAULT_RADIUS, keyWord);
                            }
                            KeyboardUtils.hideSoftInput(MapActivity.this);
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
        drClear = ContextCompat.getDrawable(this, R.drawable.ic_clear_gray_light);
        if (drClear != null) {
            drClear.setBounds(0, 0, 45, 45);
        }
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtils.isEmpty(s)) {
                    etSearch.setCompoundDrawables(null, null, null, null);
                }
                else {
                    etSearch.setCompoundDrawables(null, null, drClear, null);
                }
            }
        });
        DrawableUtil drawableUtil = new DrawableUtil(etSearch);
        drawableUtil.setListener(new DrawableUtil.OnDrawableListener() {

            @Override
            public void onLeft(View v, Drawable left) {

            }

            @Override
            public void onRight(View v, Drawable right) {
                etSearch.getText().clear();
                etSearch.setCompoundDrawables(null, null, null, null);
            }
        });
    }

    /**
     * 申请权限
     */
    @SuppressLint("CheckResult")
    private void requestPermission() {
        String[] permissions = new String[] { Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION };
        RxPermissions rp = new RxPermissions(this);
        rp.requestEach(permissions).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                if (permission.granted) {
                    initMapView();
                }
                else {
                    if (permission.shouldShowRequestPermissionRationale) {
                        String tip = "%s";
                        switch (permission.name) {
                            case Manifest.permission.ACCESS_FINE_LOCATION:
                                tip = "位置";
                                break;
                            case Manifest.permission.READ_PHONE_STATE:
                                tip = "读写设备状态";
                                break;
                            case Manifest.permission.READ_EXTERNAL_STORAGE:
                            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                                tip = "存储";
                                break;
                            case Manifest.permission.ACCESS_COARSE_LOCATION:
                                tip = "基站位置";
                                break;
                            default:
                                tip = "";
                                break;
                        }
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        showMessage(String.format("拒绝%s权限将无法正常使用本应用", tip));
                    }
                    else {
                        // 用户拒绝了该权限，并且选中『不再询问』，提醒用户手动打开权限
                        showMessage("拒绝权限将无法正常使用本应用，请在设置中手动打开");
                    }
                }
            }
        });
    }

    /**
     * 初始化地图
     */
    private void initMapView() {
        // 初始化地图控制器对象
        aMap = mMapView.getMap();
        // 控件是指浮在地图图面上的一系列用于操作地图的组件，例如缩放按钮、指南针、定位按钮、比例尺等。
        // UiSettings 类用于操控这些控件，以定制自己想要的视图效果 api查看:https://lbs.amap.com/api/android-sdk/guide/interaction-with-map/control-interaction/
        mUiSettings = aMap.getUiSettings();
        // 隐藏缩放按钮
        mUiSettings.setZoomControlsEnabled(false);
        // 隐藏定位按钮
        mUiSettings.setMyLocationButtonEnabled(false);
        // 可触发定位并显示当前位置
        //        aMap.setMyLocationEnabled(true);
        // 比例尺控件
        mUiSettings.setScaleControlsEnabled(true);
        locate();
        // 地图点击监听
        aMap.setOnMapClickListener(this);
        // 地图触摸监听
        aMap.setOnMapTouchListener(this);

    }

    /**
     * 定位
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//只定位一次。
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE) ;//定位一次，且将视角移动到地图中心点。
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW) ;//连续定位、且将视角移动到地图中心点，定位蓝点跟随设备移动。（1秒1次定位）
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);//连续定位、且将视角移动到地图中心点，地图依照设备方向旋转，定位点会跟随设备移动。（1秒1次定位）
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）默认执行此种模式。
     * //以下三种模式从5.1.0版本开始提供
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，并且蓝点会跟随设备移动。
     * myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，地图依照设备方向旋转，并且蓝点会跟随设备移动。
     */
    private void locate() {
        loadingView.setVisibility(View.VISIBLE);
        aMap.setMyLocationEnabled(false);// 可触发定位并显示当前位置
        // 实现定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);
        myLocationStyle.interval(3000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);// 设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(false); // 设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        //设置希望展示的地图缩放级别 https://lbs.amap.com/api/android-sdk/guide/interaction-with-map/method-interaction/?sug_index=0
        // 地图的缩放级别一共分为 17 级，从 3 到 19。数字越大，展示的图面信息越精细。
        CameraUpdate cameraUpdate = CameraUpdateFactory.zoomTo(16);
        // 带有移动过程的动画
        aMap.animateCamera(cameraUpdate);
        // 回调方法获取经纬度信息
        aMap.setOnMyLocationChangeListener(location -> {
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            if (followMove) {
                aMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
            //从location对象中获取经纬度信息，地址描述信息，建议拿到位置之后调用逆地理编码接口获取（获取地址描述数据章节有介绍）
            Timber.d(" 获取定位经度:%s", String.valueOf(location.getLongitude()));
            Timber.d(" 获取定位纬度:%s", String.valueOf(location.getLatitude()));
            this.lat = location.getLatitude();
            this.lng = location.getLongitude();
            // 当无法获取定位时
            if (lat == 0 && lng == 0) {
                showMessage("暂未获取到位置信息");
                return;
            }
            this.curLatLng = new LatLng(location.getLatitude(), location.getLongitude());
            if (firstLocated) {
                // 获取到当前定位后请求后台获取附近停车场
                mPresenter.loadLotsAround(curLatLng);
                firstLocated = false;
            }
            loadingView.setVisibility(View.GONE);
        });
    }

    /**
     * 通过地图SDK搜索当前定位附近的停车场，为后台造数据用
     */
    private void searchLotsAround(String keyWord, String cityCode) {
        PoiSearch.Query query = new Query(keyWord, Const.PoiType.PARKING_TYPE, cityCode);
        //构造 PoiSearch.Query 对象，通过 PoiSearch.Query(String query, String ctgr, String city) 设置搜索条件。keyWord表示搜索字符串，
        //第二个参数表示POI搜索类型，二者选填其一，选用POI搜索类型时建议填写类型代码，码表可以参考下方（而非文字）
        //cityCode表示POI搜索区域，可以是城市编码也可以是城市名称，也可以传空字符串，空字符串代表全国在全国范围内进行搜索
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(1);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(MapActivity.this, query);
        //设置周边搜索的中心点以及半径
        //        LatLonPoint latLonPoint = new LatLonPoint(31.491889578857243, 104.68659594377645); // 默认以天府学院（绵阳校区）为中点
        if (lat == 0 || lng == 0) {
            showMessage("未获取到当前位置信息，请重新定位");
            return;
        }
        LatLonPoint latLonPoint = new LatLonPoint(lat, lng);
        // 半径为1000米
        poiSearch.setBound(new SearchBound(latLonPoint, 1000, true));
        poiSearch.setOnPoiSearchListener(MapActivity.this);
        // 发送请求
        poiSearch.searchPOIAsyn();
        /* 定义 Marker 点击事件监听
		   marker 对象被点击时回调的接口
		   返回 true 则表示接口已响应事件，否则返回false
		 */
        AMap.OnMarkerClickListener markerClickListener = marker -> {

            return false;
        };
        // 绑定 Marker 被点击事件
        aMap.setOnMarkerClickListener(markerClickListener);

    }

    /**
     * POI搜索结果回调
     */
    @Override
    public void onPoiSearched(PoiResult result, int code) {
        //code 为1000 时成功,其他为失败
        if (code == AMapException.CODE_AMAP_SUCCESS) {
            // 解析result   获取搜索poi的结果
            if (result != null && result.getQuery() != null) {
                if (aMap.getMapScreenMarkers().size() > 0) {
                    aMap.clear();
                }
                //				if (result.getQuery().equals(query)) {  // 是否是同一条
                ArrayList<ParkingLot> data = new ArrayList<ParkingLot>();//自己创建的数据集合
                // 取得第一页的poiitem数据，页数从数字0开始
                //poiResult.getPois()可以获取到PoiItem列表
                List<PoiItem> poiItems = result.getPois();
                if (ObjectUtils.isEmpty(poiItems)) {
                    //若当前城市查询不到所需POI信息，可以通过result.getSearchSuggestionCitys()获取当前Poi搜索的建议城市
                    List<SuggestionCity> suggestionCities = result.getSearchSuggestionCitys();
                    showSuggestCity(suggestionCities);
                }

                //如果搜索关键字明显为误输入，则可通过result.getSearchSuggestionKeywords()方法得到搜索关键词建议。
                List<String> suggestionKeywords = result.getSearchSuggestionKeywords();

                //解析获取到的PoiItem列表
                for (PoiItem item : poiItems) {
                    //获取经纬度对象
                    LatLonPoint llp = item.getLatLonPoint();
                    double lon = llp.getLongitude();
                    double lat = llp.getLatitude();
                    //返回POI的名称
                    String title = item.getTitle();
                    //返回POI的地址
                    String snippet = item.getSnippet();
                    // 照片
                    List<Photo> photos = item.getPhotos();
                    // 生成附近停车场信息（给后台造数据用）
                    ParkingLot info = genLotInfo(title, lat, lon, snippet);
                    data.add(info);
                    // 在地图上绘制点
                    LatLng latLng = new LatLng(lat, lon);
                    drawLatLng(latLng, title, snippet);
                }
                LogUtils.e(GsonUtils.toJson(data));
                //				}
            }
            else {
                showMessage("无搜索结果");
            }
        }
        else {
            showMessage("错误码" + code);
        }

    }

    /**
     * 根据经纬度绘制点
     */
    private void drawLatLng(LatLng latLng, String title, String snippet) {
        MarkerOptions options = new MarkerOptions()
                //自定义图标 不添加为蓝色点点
                .icon(BitmapDescriptorFactory.fromBitmap(
                        BitmapFactory.decodeResource(getResources(), R.drawable.ic_parking_lot)))
                //在地图上标记位置的经纬度值。必填参数
                .position(latLng)
                //点标记的标题
                .title(title)
                //点标记的内容
                .snippet(snippet)
                //点标记是否可拖拽
                .draggable(true)
                //点标记是否可见
                .visible(true)
                //点标记的透明度
                .alpha(1.0f)
                //设置marker平贴地图效果,可以双指下拉地图查看效果
                .setFlat(false);
        aMap.addMarker(options);
    }

    private ParkingLot genLotInfo(String title, double lat, double lon, String text) {
        ParkingLot info = new ParkingLot();
        info.setSpaceTotal(1000);
        info.setSpaceFree(500);
        info.setPrice(2.0);
        info.setPayWay(1);
        info.setName(title);
        info.setLocation(text);
        info.setLatitude(lat);
        info.setLongitude(lon);
        return info;
    }

    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:" + cities.get(i)
                                                                                  .getCityCode() + "城市编码:" + cities
                    .get(i)
                    .getAdCode() + "\n";
        }
        Timber.e(infomation);

    }

    /**
     * 地图点击回调经纬度信息
     */
    @Override
    public void onMapClick(LatLng latLng) {
        if (KeyboardUtils.isSoftInputVisible(this)) {
            KeyboardUtils.hideSoftInput(this);
        }
        // todo 下面注释造数据放开
        this.lat = latLng.latitude;
        this.lng = latLng.longitude;
        Timber.d("点击经度%s", latLng.longitude);
        Timber.d("点击纬度%s", latLng.latitude);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ToastUtils.showShort(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void showLotAround(List<ParkingLot> list) {
        clearMarkers();
        for (ParkingLot lot : list) {
            LatLng latLng = new LatLng(lot.getLatitude(), lot.getLongitude());
            drawLatLng(latLng, lot.getName(), lot.getLocation());
        }
        showLotList(list, "附近停车场");
    }

    @Override
    public void showResultList(List<ParkingLot> list) {
        clearMarkers();
        for (ParkingLot lot : list) {
            LatLng latLng = new LatLng(lot.getLatitude(), lot.getLongitude());
            drawLatLng(latLng, lot.getName(), lot.getLocation());
        }
        showLotList(list, "搜索结果");
    }

    /**
     * 底部弹框停车场列表
     */
    private void showLotList(List<ParkingLot> list, String title) {
        View rootView = LayoutInflater.from(this).inflate(R.layout.layout_dialog, mMapView, false);
        TextView tvTitle = rootView.findViewById(R.id.tvTitle);
        tvTitle.setText(String.format(title + "（%s）", list.size()));
        RecyclerView rvLots = rootView.findViewById(R.id.recyclerView);
        LotsAdapter adapter = new LotsAdapter(list);
        rvLots.setLayoutManager(new LinearLayoutManager(this));
        rvLots.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> switchToLotDetailPage(
                adapter.getData().get(position)));
        adapter.setOnItemChildClickListener((adapter12, view, position) -> {
            ParkingLot item = adapter.getData().get(position);
            if (item == null) {
                showMessage("参数错误");
                return;
            }
            if (view.getId() == R.id.tvLotDistance) {
                MyUtils.startNavigate(MapActivity.this, curLatLng,
                        new LatLng(item.getLatitude(), item.getLongitude()), item.getName(),
                        new NaviInfoCallback(new NaviInfoCallback.OnArriveCallback() {
                            @Override
                            public void onArrive() {
                                Log.d(TAG, "onArrive: ");
                                aMap.getMyLocation();
//                                aMap.animateCamera(CameraUpdateFactory.changeLatLng(curLatLng));
                            }
                        }));
                // 跳转到高德地图
                //                MyUtils.startAMap(MapActivity.this, item.getName(), item.getLatitude(), item.getLongitude());
            }
        });
        AnyLayer.dialog(this)
                .contentView(rootView)
                .backgroundColorRes(R.color.white)
                .gravity(Gravity.BOTTOM)
                .cancelableOnTouchOutside(true)
                .cancelableOnClickKeyBack(true)
                .dragDismiss(DragLayout.DragStyle.Bottom)
                .animator(new Layer.AnimatorCreator() {
                    @Override
                    public Animator createInAnimator(View target) {
                        return AnimatorHelper.createBottomInAnim(target);
                    }

                    @Override
                    public Animator createOutAnimator(View target) {
                        return AnimatorHelper.createBottomOutAnim(target);
                    }
                })
                .show();

    }

    /**
     * 跳转到停车场详情界面
     */
    private void switchToLotDetailPage(ParkingLot lot) {
        Intent intent = new Intent(this, LotDetailActivity.class);
        intent.putExtra(Const.Keys.KEY_PARKING_LOT, lot);
        intent.putExtra(Const.Keys.KEY_CUR_LOCATION, curLatLng);
        launchActivity(intent);
    }

    private void clearMarkers() {
        if (aMap == null) {
            return;
        }
        if (aMap.getMapScreenMarkers().size() > 0) {
            aMap.clear();
        }
    }

    /**
     * 地图触摸监听回调
     */
    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (followMove) {
            //用户拖动地图后，不再跟随移动，需要跟随移动时再把这个改成true
            followMove = false;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRelogin(String s) {
        UserSettings.getInstance().setLogin(false);
        launchActivity(new Intent(this, LoginActivity.class));
        finish();
    }
}
